package cn.xuyun.cc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.xuyun.cc.tcp.bean.CommandReq;
import cn.xuyun.cc.tcp.service.MongoService;

/**
 * Servlet implementation class GetLastCmdServlet
 */
@WebServlet("/st/GetLastCmd")
public class GetLastCmdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 * 
	 * 
	 * 
	 * <cmdlist>
<cmd>  /////命令序列号、命令标识码、命令开始时间、命令结束时间、命令执行进度（百分比）
  <command></command> --命令英文描述CMD_POWER_ON
<key></key> --命令唯一标识，A请求时发送的
  <begintime></begintime> --命令开始时间 2012-10-29 10:00:01
  <endtime></endtime> --命令结束时间，如果超时或者完成，就设置，否则为空
  <finished></finished>  已完成比例，46/200
</cmd>
……
</cmdlist>
	 * 
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
String user=request.getParameter("user");
		
		int count = Integer.parseInt(request.getParameter("count"));
		
		
		List<CommandReq> list=MongoService.getLastCmd(user, count);
		
		StringBuilder sb = new StringBuilder();
		sb.append("<cmdlist>");
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(CommandReq cr:list)
		{
			sb.append("<cmd>");
			sb.append("<command>"+cr.getCmdstr()+"</command>");
			sb.append("<key>"+cr.get_id()+"</key>");
			sb.append("<begintime>"+sdf.format(new Date(cr.getBegin_time()))+"</begintime>");
			if(cr.getEnd_time()==0)
			{
				sb.append("<endtime>"+sdf.format(new Date())+"</endtime>");
			}else{
				sb.append("<endtime>"+sdf.format(new Date(cr.getEnd_time()))+"</endtime>");
			}
			sb.append("<finished>"+cr.getFinished()+"/"+cr.getDevice_id().size()+"</finished>");
			sb.append("</cmd>");
		}
		sb.append("</cmdlist>");
		
		PrintWriter out=response.getWriter();
		
		out.print(sb.toString());
	}

}
